package rpc.core.plugin.impl.proxy;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

/*********
 *
 *
 *@author 197
 *@date 2020/8/3 10:53
 *
 **/


public class SqlFormatUtils {

  private static final String patternString = "\\#\\{[a-zA-Z0-9\\s]+\\}";
  private static final Pattern pattern = Pattern.compile(patternString);

  public static SqlFormat sqlFormat(String sql) {
    if (StringUtils.isBlank(sql)) {
      throw new RuntimeException("sql is null or blank");
    }
    Matcher matcher = pattern.matcher(sql);
    List<String> fields = new ArrayList<>();
    while (matcher.find()) {
      fields.add(matcher.group(0));
    }
    fields = fields.stream().map(f -> f.substring(2, f.length() - 1).trim()).collect(Collectors.toList());
    return new SqlFormat().setSql(sql.replaceAll(patternString, "?")).setFields(fields);
  }

  static class SqlFormat {

    private String sql;

    private List<String> fields;

    public String getSql() {
      return sql;
    }

    public SqlFormat setSql(String sql) {
      this.sql = sql;
      return this;
    }

    public List<String> getFields() {
      return fields;
    }

    public SqlFormat setFields(List<String> fields) {
      this.fields = fields;
      return this;
    }

    @Override
    public String toString() {
      return "SqlFormat{" +
          "sql='" + sql + '\'' +
          ", fields=" + fields +
          ", hasParam=" + hasParam() +
          '}';
    }

    public boolean hasParam() {
      return CollectionUtils.isNotEmpty(fields);
    }
  }
}
